package com.xxx.lib

import android.app.Application
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.CleanUtils
import com.blankj.utilcode.util.ProcessUtils
import com.blankj.utilcode.util.Utils
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.manager.PictureCacheManager
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

open class BaseLibApplication : Application() {

    companion object {
        /**
         * 初始化第三方SDK，适配监管要求，同意隐私政策后才初始化
         */
        fun initSDK() {
            if (ProcessUtils.isMainProcess()) {  //在主进程中做相关初始化，避免多进程重复初始化
                // 腾讯tbs初始化
                val map = HashMap<String, Any>().also {
                    it[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
                    it[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
                }
                QbSdk.initTbsSettings(map as Map<String, Any>)
                QbSdk.setDownloadWithoutWifi(true)
                QbSdk.initX5Environment(Utils.getApp(), null)
                //ARouter路由初始化
                if (AppUtils.isAppDebug()) {
                    ARouter.openLog()
                    ARouter.openDebug()
                }
                ARouter.init(Utils.getApp())
                //垃圾清理
                clear()
            }
        }

        /**
         * 垃圾清理
         */
        private fun clear() {
            CoroutineScope(Dispatchers.IO).launch {
                //清理部分临时文件
                CleanUtils.cleanCustomDir(PathConfig.DIR_CACHE_PICTURESELECTOR)
                PictureCacheManager.deleteCacheDirFile(Utils.getApp(), SelectMimeType.ofImage())
                PictureCacheManager.deleteAllCacheDirFile(Utils.getApp())
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        //通用工具库初始化
        Utils.init(this)
    }
}